package com.nacos.controller;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

@RestController
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    //注入服务发现接口
    @Autowired
    private DiscoveryClient discoveryClient;

    // nacos 调用
    @GetMapping("/consumer")
    public void getConsumer() {
        //获取服务名称为product-service的服务，得到的是一个List的实例集合
        List<String> services = discoveryClient.getServices();
        //因为有可能有多个实例
        List<ServiceInstance> instances = discoveryClient.getInstances("produce-service");
        //获取第一个实例，也就是获取的实例列表中的第一个实例
        ServiceInstance serviceInstance = instances.get(0);
        //获取这个实例的端口
        int port = serviceInstance.getPort();
        //获取这个实例的访问地址
        String host = serviceInstance.getHost();
        System.out.println("获取服务名为order-service的第一个服务：" + serviceInstance);
        System.out.println("获取服务名为order-service的第一个服务port：" + port);
        System.out.println("获取服务名为order-service的第一个服务host：" + host);
    }


    @GetMapping("/consume/{name}")
    public void getConsumer(@PathVariable("name") String name) {
        System.out.println("查询服务:" + name);
        //远程调⽤商品微服务,查询商品信息
        List<ServiceInstance> instances = discoveryClient.getInstances("produce-service");
        ServiceInstance serviceInstance = instances.get(0);
        int port = serviceInstance.getPort();
        String host = serviceInstance.getHost();
        String product = restTemplate.getForObject("http://" + host + ":" + port + "/produce/" + name, String.class);
        System.out.println("已测试通过，返回信息:" + product);
    }
}